package com.stars.pao.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.crypto.SecureUtil;
import com.stars.pao.aicloud.util.MinIoUtil;
import com.stars.pao.aicloud.util.NameUtil;
import com.stars.pao.aicloud.util.ResponseEntity;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import java.util.concurrent.TimeUnit;
@Tag(name = "验证码控制器")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private MinIoUtil minIoUtil;

    @Resource
    private RedisTemplate redisTemplate;

    //生成验证码
    @PostMapping("/create")
    public ResponseEntity creatCaptcha(HttpServletRequest request) throws  InternalException, IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException {
        String url = "";
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        String fileName = NameUtil.getCaptchaName(request);

        try(InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())) {
            url =   minIoUtil.upload(fileName, inputStream, "image/png");
            String code = lineCaptcha.getCode(); //正确的验证码
            redisTemplate.opsForValue().set(fileName,code,60, TimeUnit.SECONDS); //将名称和对应的验证码存入redis，按String类型存储的此处,并设置过期时间为60s
        }
        return ResponseEntity.succ(url);
    }
}
